#include "canvas.hpp"

Canvas::Canvas(Window* window,SDL_Rect& rect,SDL_Color background):Control(window){
    _t=window->renderer->CreateTexture(rect.w,rect.h);
    this->background=background;
    auto r=window->renderer;
    r->SetTarget(_t);
    r->SetColor(background);
    r->Clear();
    r->SetTarget(NULL);
}
Canvas::Canvas(Window* window):Control(window){
    background=Color::White;
    _t=window->renderer->CreateTexture(1,1);
}
void Canvas::DrawLine(SDL_Point p1,SDL_Point p2,SDL_Color color){
    auto r=_belong->renderer;
    r->SetTarget(_t);
    r->SetColor(color);
    r->DrawLine(p1,p2);
    r->SetTarget(NULL);
}
void Canvas::DrawRect(SDL_Rect& rect,SDL_Color color){
    auto r=_belong->renderer;
    r->SetTarget(_t);
    r->SetColor(color);
    r->DrawRect(rect);
    r->SetTarget(NULL);
}
void Canvas::FillRect(SDL_Rect& rect,SDL_Color color){
    auto r=_belong->renderer;
    r->SetTarget(_t);
    r->SetColor(color);
    r->FillRect(rect);
    r->SetTarget(NULL);
}
void Canvas::DrawPoint(SDL_Point p,SDL_Color color){
    auto r=_belong->renderer;
    r->SetTarget(_t);
    r->SetColor(color);
    r->DrawPoint(p);
    r->SetTarget(NULL);
}
void Canvas::DrawTexture(SDL_Texture* texture,SDL_Rect& rect){
    auto r=_belong->renderer;
    r->SetTarget(_t);
    r->DrawTexture(NULL,&rect,texture);
    r->SetTarget(NULL);
}
void Canvas::DrawText(SDL_Point p,Font* font,char* text,SDL_Color color){
    auto r=_belong->renderer;
    r->SetTarget(_t);
    auto t=r->RenderText(font,text,color);
    SDL_Rect rect;
    rect.x=p.x,rect.y=p.y;
    SDL_QueryTexture(t,NULL,NULL,&rect.w,&rect.h);
    r->DrawTexture(NULL,&rect,t);
    SDL_DestroyTexture(t);
    r->SetTarget(NULL);
}
void Canvas::SetSize(int w,int h){
    _area.w=w,_area.h=h;
    auto r=_belong->renderer;
    auto t=r->CreateTexture(w,h);
    r->SetTarget(t);
    r->SetColor(background);
    r->Clear();
    r->DrawTexture(NULL,NULL,_t);
    SDL_DestroyTexture(_t);
    _t=t;
    r->SetTarget(NULL);
}
void Canvas::Clear(){
    auto r=_belong->renderer;
    r->SetTarget(_t);
    r->SetColor(background);
    r->Clear();
    r->SetTarget(NULL);
}
Canvas::~Canvas(){SDL_DestroyTexture(_t);}